#include "disp_driver.h"
#include <fcntl.h>
#include <linux/spi/spidev.h>
#include <sys/ioctl.h>
#include <unistd.h>

int spi_device;
extern configuration config;
static int g_spifd = 0;

int dirver_spi_init() {
    // 打开 SPI 设备
    spi_device = open(config.disp_path, O_RDWR);
    if (spi_device < 0) {
        perror("Error opening SPI device");
        return 1;
    }

    g_spifd = spi_device;

    // 设置 SPI 模式、速率等属性
    uint8_t mode = config.spi_mode;
    uint32_t speed = config.spi_speed_mh * 1000 * 1000;
    if (ioctl(spi_device, SPI_IOC_WR_MODE, &mode) < 0) {
        perror("Error setting SPI mode");
        close(spi_device);
        return 1;
    }
    if (ioctl(spi_device, SPI_IOC_WR_MAX_SPEED_HZ, &speed) < 0) {
        perror("Error setting SPI speed");
        close(spi_device);
        return 1;
    }

    return 0;
}

void dirver_spi_deinit() {
    // 关闭 SPI 设备
    close(spi_device);
    g_spifd = 0;
}

void spi_write(void *data, uint16_t length) {
    if (write(g_spifd, data, length) < 0) {
        perror("Error in SPI transfer");
    };
}

#define SPI_WRITE_SIZE 4096

void dirver_spi_send_data(void *data, uint16_t length) {
    int32_t len = length;
    while (len > 0) {
        if (len < SPI_WRITE_SIZE) {
            spi_write(data, len);
        } else {
            spi_write(data, SPI_WRITE_SIZE);
        }
        data = data + SPI_WRITE_SIZE;
        len = len - SPI_WRITE_SIZE;
    }
}